(function(){
    var elements = [];
    function Snake(width, height, direction){
        this.width = width || 20;
        this.height = height || 20;
        this.direction = direction || 'right';
        this.body = [
            {x: 3, y: 2, color: 'red'},
            {x: 2, y: 2, color: 'yellow'},
            {x: 1, y: 2, color: 'yellow'}
        ];
        this.score = 0;
    }
    Snake.prototype.init = function(map){
        remove();
        for(var i=0; i< this.body.length; i++ ){
              var ele = this.body[i];
              var div = document.createElement('div');
              map.appendChild(div);
              elements.push(div);
              div.style.position = 'absolute';
              div.style.width =  this.width + 'px';
              div.style.height = this.height + 'px';
              div.style.left = ele.x * this.width + 'px';
              div.style.top = ele.y * this.height + 'px';
              div.style.background = ele.color;
        }
    };
    Snake.prototype.move = function(food,map){
        for(var i = this.body.length-1; i>0; i--){
             this.body[i].x = this.body[i-1].x;
             this.body[i].y = this.body[i-1].y;
        }
        switch(this.direction){
            case 'left':  this.body[0].x -= 1; break;
            case 'right': this.body[0].x += 1; break;
            case 'top': this.body[0].y -= 1; break;
            case 'bottom': this.body[0].y += 1; break;
        }
        if(this.body[0].x == food.x && this.body[0].y == food.y){
             this.body.push({
                 x: this.body[this.body.length-1].x,
                 y: this.body[this.body.length-1].y,
                 color: this.body[this.body.length-1].color
             });
             this.score++;
             food.init(map);
        }
        this.init(map);
    };
    Snake.prototype.scoreFn = function(){
        return this.score;
    }
    function remove(){
        for(var i= elements.length-1; i >=0; i--){
            elements[i].parentNode.removeChild(elements[i]);
            elements.splice(i,1);
        }
    }

    window.Snake = Snake;
}());